// index.js
const express = require('express')
const { ApolloServer, gql } = require('apollo-server-express')
const db = require('./db.js')
const typeDefs = gql`
  type Student {
    sname: String
    age: Int
  }
  type Query {
    hello: [Student!]!
  }
`

const resolvers = {
  Query: {
    hello: async (parent, args, context) => {
      let res = await context.db.getData()
      // 这里获取到数据源对象之后就可以非常方便的获取需要的数据,从而返回给客户端
      console.log(JSON.parse(res))
      return JSON.parse(res)
    }
  }
}
const context = () => {
  return {
    db: db
  }
}

const server = new ApolloServer({ typeDefs, resolvers, context })

const app = express()
server.applyMiddleware({ app })

app.listen({ port: 4000 }, () => console.log('Now browse to http://localhost:4000' + server.graphqlPath))
